package com.jn.mvvm2.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.mvvm2.R;
import com.jn.mvvm2.databinding.PetItemBinding;
import com.jn.mvvm2.entity.Pet;

import java.util.List;

public class PetAdapter extends RecyclerView.Adapter<PetAdapter.PetViewHolder> {
    private List<Pet> petList;

    public PetAdapter(List<Pet> petList) {
        this.petList = petList;
    }

    @NonNull
    @Override
    public PetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        PetItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.pet_item, parent, false);
        return new PetViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull PetViewHolder holder, int position) {
        Pet pet = petList.get(position);
        holder.bind(pet);
    }

    @Override
    public int getItemCount() {
        return petList == null ? 0 : petList.size();
    }

    public static class PetViewHolder extends RecyclerView.ViewHolder {
        private final PetItemBinding binding;

        public PetViewHolder(PetItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        public void bind(Pet pet) {
            binding.setPet(pet);
            binding.executePendingBindings();
            Glide.with(binding.imageView.getContext()).load(pet.getCoverURL()).into(binding.imageView);
        }
    }
}